package com.tac.service.impl;

import com.tac.common.result.Result;
import com.tac.common.utils.UserThreadLocal;
import com.tac.dao.UserDao;
import com.tac.pojo.User;
import com.tac.service.UserService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    //获取验证码
    public Result getCode(String username) {
        String code = new Random().nextInt(8999) + 1000 + "";
        redisTemplate.opsForValue().set(username, code, 60, TimeUnit.SECONDS);
        return Result.success(code);
    }

    //登录
    public Result login(User user, String code) {
        if (code == null) {
            return Result.error("验证码为空");
        }
        String o = (String) redisTemplate.opsForValue().get(user.getUsername());
        if (!code.equals(o)) {
            return Result.error("验证码错误");
        }
        User userByName = userDao.getUserByName(user.getUsername());
        if (userByName == null) {
            return Result.error("用户不存在");
        }
        String s = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (!s.equals(userByName.getPassword())) {
            return Result.error("密码错误");
        }
        JwtBuilder builder = Jwts.builder();
        String token = builder.signWith(SignatureAlgorithm.HS256, "tac666")
                .setSubject(userByName.getId() + "")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                .compact();
        return Result.success(token);
    }

    //注册
    public Result savaUser(User user) {
        User userByName = userDao.getUserByName(user.getUsername());
        if(userByName!=null){
            return Result.error("用户名已存在");
        }
        Integer integer = userDao.savaUser(user);
        if(integer<=0){
            return Result.error("注册失败");
        }
        return Result.success(null);
    }

    //更新头像
    public Result updateHead(String head){
        Integer id = UserThreadLocal.getId();
        Integer integer = userDao.updateHead(head, id);
        if(integer<=0){
            return Result.error("更新头像失败");
        }
        return Result.success(null);
    }
}
